class InterceptorsManage {
  chain = []
  use(fullfield, rejected) {
    this.chain.push({ fullfield, rejected })
  }
  query() {
    return this.chain
  }
}
class Axios {
  constructor() {
    this.interceptors = {
      request: new InterceptorsManage(),
      response: new InterceptorsManage()
    }
  }
  request(option) {
    const chain = [{ fullfield: ajax, rejected: undefined }]
    this.interceptors.request.forEach(o => {
      chain.unshift(o)
    })
    this.interceptors.response.forEach(o => {
      chain.push(o)
    })
    const promise = Promise.resolve(option)
    while (chain.length > 0) {
      const { fullfield, rejected } = chain.shift()
      promise = promise.then(fullfield, rejected)
    }
    return promise
  }
  ajax(option) {
    return new Promise(resolve => {
      const { url, data } = option
      const xhr = new XMLHttpRequest()
      xhr.open(method, url)
      xhr.onload = function () {
        resolve(xhr.response)
      }
      xhr.send(data)
    })
  }
}

;['get', 'post', 'put', 'delete', 'head', 'options'].forEach(method => {
  Axios.prototype[method] = function (url, data) {
    this.request({ url, data })
  }
})

function extend(aObj, bObj, context) {
  Object.keys(bObj).forEach(key => {
    Object.defineProperty(aObj, key, {
      get() {
        return bObj[key].bind(context)
      },
      enumerable: true
    })
  })
}

function createAxios() {
  const axios = new Axios()
  const request = axios.request.bind(axios)
  extend(request, Axios.prototype, axios)
  extend(request, axios, axios)
  return request
}

export default createAxios
